package com.gitee.attendance.service.impl;

import java.io.FileInputStream;
import java.util.UUID;

import com.gitee.attendance.entity.Task;
import com.gitee.attendance.entity.User;
import com.gitee.attendance.service.HomeServiceI;
import com.gitee.attendance.util.baidu.CurrencyUtil;
import com.gitee.attendance.util.baidu.FaceUtil;
import com.gitee.attendance.util.base64.Base64Util;
import com.gitee.attendance.util.rides.RedisUtil;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("HomeService")
@Transactional
public class HomeServiceImpl implements HomeServiceI {

    private Logger logger = LoggerFactory.getLogger(HomeServiceImpl.class);

    @Autowired
    private FaceUtil faceUtil;

    @Autowired
    private Base64Util base64Util;

    @Autowired
    private RedisUtil redis;

    public String faceMatch(FileInputStream fileInputStream, String userCode) throws Exception {
        byte[] bytes1 = base64Util.getFileInputStream(fileInputStream);
        String base1 = base64Util.encode(bytes1);
        JSONObject faceVerifyRes = faceUtil.faceVerify(base1);

        Number errorCode = (Number) faceVerifyRes.get(CurrencyUtil.ERROR_CODE);

        if (errorCode.doubleValue() == 0) {
            faceVerifyRes = faceVerifyRes.getJSONObject(CurrencyUtil.RESULT);
            logger.debug(faceVerifyRes.toString());
            Number faceLiveness = (Number) faceVerifyRes.get(CurrencyUtil.FACE_LIVENESS);
            Number frr_1e_2 = (Number) faceVerifyRes.getJSONObject(CurrencyUtil.THRESHOLDS).get(CurrencyUtil.FRR_1E);
            if (faceLiveness.doubleValue() >= frr_1e_2.doubleValue()) {
                Object resultObj = redis.get(User.REDIS_KEY + userCode);
                if (resultObj == null) {
                    return "ERROR:未查询到相关结果 " + User.REDIS_KEY + userCode;
                }
                String result = resultObj.toString();
                logger.debug(result);
                JSONObject faceMatchRes;

                try {
                    faceMatchRes = new JSONObject(result);
                } catch (Exception e) {
                    return "ERROR:查询结果格式异常 " + User.REDIS_KEY + userCode;
                }

                String userName = faceMatchRes.getString(User.USERNAME);
                String base2 = faceMatchRes.getString(User.USERFACE);

                faceMatchRes = faceUtil.faceMatch(base1, CurrencyUtil.BASE64, base2, CurrencyUtil.BASE64);
                errorCode = (Number) faceMatchRes.get(CurrencyUtil.ERROR_CODE);
                if (errorCode.doubleValue() == 0) {
                    faceMatchRes = faceMatchRes.getJSONObject(CurrencyUtil.RESULT);
                    Number similarityDegree = (Number) faceMatchRes.get(CurrencyUtil.SCORE);
                    if (similarityDegree.doubleValue() >= 85) {
                        return "SUCCESS:登录成功 " + User.REDIS_KEY + userName;
                    } else {
                        return "ERROR:相似度过低，请换人或重传 ";
                    }
                } else {
                    String errorMsg = faceMatchRes.getString(CurrencyUtil.ERROR_MSG);
                    return "ERROR:" + errorMsg;
                }
            } else {
                return "ERROR:照片画质过低，请对准拍摄 ";
            }
        } else {
            String errorMsg = faceVerifyRes.getString(CurrencyUtil.ERROR_MSG);
            return "ERROR:" + errorMsg;
        }
    }

    public String attendance(User user) throws Exception {
        Task task = new Task();
        String uuid = UUID.randomUUID().toString();
        task.setUuid(uuid);
        task.setUser(user);

        if (redis.lSet(Task.REDIS_NMAE, new JSONObject(task).toString())) {
            int i = 0;
            while (true) {
                if (i == 30) {
                    return "ERROR:服务器繁忙，请重试";
                }
                try {
                    Object resultObj = redis.get(RedisUtil.REDIS_KEY_RESULT + uuid);
                    if (resultObj != null) {
                        return resultObj.toString();
                    }
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    return "ERROR:请求失败，服务器异常";
                }
                i = i + 1;
                logger.debug(user.getUserCode() + "等待" + i + "次");

            }

        } else {
            return "ERROR:请求失败，Redis异常";
        }

    }

}